<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Tools\Fun;

class CompanyAdminModel extends Model
{
    use HasFactory;
    protected $table = 'company_admin';
    protected $fillable = [
        'company_id',
        'realname',
        'username',
        'password',
        'phone',
        'role',
        'token'
    ];

    static function login($companyName, $username, $password) {
        // 验证机构是否存在
        $company = CompanyModel::where('name', $companyName)->first();
        if (!$company) {
            return ['code' => 400, 'msg' => '机构不存在'];
        }

        // 验证账号是否存在
        $admin = self::where('company_id', $company->id)
        ->where('username', $username)
        ->where('password', Fun::encodePassword($password))
        ->first();
        if (!$admin) {
            return ['code' => 400, 'msg' => '账号或密码错误'];
        }
        
        $token = md5($admin->id . $admin->username . $admin->password . time());
        // $token  = "f7d837565d1e4f92ec7c903118b5531b14ef0ecf";
        self::where('id', $admin->id)->update(['token' => $token]);
        return ['code' => 200,'msg' => '登录成功','token' => $token];
    }

    static function logout($id)
    {
        return self::where('id', $id)->update(['token' => $id]);
    }
}
